<?php

namespace seecms\controller;

use magein\utils\Tree;
use seecms\lib\builder\column\TextColumn;
use seecms\lib\builder\control\InputControl;
use seecms\lib\builder\control\RadioControl;
use seecms\lib\builder\control\TextareaControl;
use seecms\lib\Transfer;
use seecms\See;
use seecms\lib\TreeSelect;
use seecms\SeeConst;
use seecms\SeeLang;

class UserMenu extends Resource
{
    protected $table_name = 'see_menu';

    protected $page_title = '菜单列表';

    protected $dictionary_name = 'menu';

    protected $tree = true;

    protected function pageTitle(): string
    {
        return __('menu.page_title');
    }

    public function index()
    {
        $records = $this->db()->order('sort', 'asc')->select();

        $tree = Tree::init($records);
        $data = $tree->floor();

        return $this->view('permission/menu', [
            'menus' => $data
        ]);
    }

    protected function columnFilter($data)
    {
        if ($data['data'] ?? []) {
            foreach ($data['data'] as &$item) {
                $item['type_text'] = Transfer::translateMenuType($item['type']);
            }
            unset($item);
        }

        return $data;
    }

    public function columns(): array
    {
        return [
            'id.100',
            TextColumn::init('icon')->setTemplate('icon')->setWidth(80),
            'title.240',
            'name.280',
            'type_text',
            'sort',
            'status',
            'created_at',
        ];
    }

    public function controls(): array
    {
        $records = See::table()->menu->select();
        $tree = new TreeSelect($records);
        $options = $tree->options();

        return [
            ['parent_id', 'select', $options],
            'title',
            InputControl::init('url')->setDescription(SeeLang::menu('redirect_url_tip')),
            InputControl::init('icon'),
            RadioControl::init('type')->setOptions(Transfer::translateMenuType())->setValue(1),
            RadioControl::init('open_type')->setOptions(Transfer::translateMenuOpenType())->setDescription(SeeLang::menu('open_type_tip'))->setValue(SeeConst::MENU_OPEN_TYPE_IFRAME),
            InputControl::init('remark')->setRequired(),
            TextareaControl::init('extent')->setRequired(),
            InputControl::init('sort')->setValue(9999),
            'status',
        ];
    }
}